package com.java.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * zip包处理工具
 * 
 * @author Kevin
 *
 */
public class ZipFileUtil {

	/**
	 * 传入解压后文件夹集合，返回file集合
	 * 
	 * @param zips
	 * @return
	 */
	public static List<File> batchHandleZips(List<String> paths) {
		try {
			List<File> files = new ArrayList<File>();
			for (String parentPath : paths) {
				List<File> currentFiles = getFilesByParentPath(parentPath);
				if (currentFiles != null) {
					files.addAll(currentFiles);
				}
			}
			return files;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 传入路径，递归获得所有子文件
	 * 
	 * @param parentPath
	 * @return
	 */
	public static List<File> getFilesByParentPath(String parentPath) {
		try {
			File file = new File(parentPath);
			if (file.exists()) {
				List<File> files = new ArrayList<File>();
				if (file.isDirectory()) {
					String[] filelist = file.list();
					for (int i = 0; i < filelist.length; i++) {
						File childFile = new File(parentPath + File.separator + filelist[i]);
						if (!childFile.isDirectory()) {
							files.add(childFile);
						} else if (childFile.isDirectory()) {
							files.addAll(getFilesByParentPath(childFile.getPath()));
						}
					}
				}
				return files;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 批量删除缓存文件
	 * 
	 * @param fileNames
	 */
	public static void deleteCacheFiles(String... fileNames) {
		for (String s : fileNames) {
			deletefile(s);
		}
	}

	/**
	 * 递归删除文件
	 * 
	 * @param delpath
	 */
	public static void deletefile(String delpath) {
		try {
			File file = new File(delpath);
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + File.separator + filelist[i]);
					if (!delfile.isDirectory()) {
						delfile.delete();
					} else if (delfile.isDirectory()) {
						deletefile(delpath + File.separator + filelist[i]);
					}
				}
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
